"""
@File    :   global_exception.py
@Time    :   2024/02/22 17:25:14
@Author  :   Qrj
@Email   :   923207736@qq.com
@description   :   全局异常处理
"""

from fastapi import Request
from fastapi.exceptions import HTTPException, RequestValidationError

from src.enums.http_response_code import HttpResponseEnum
from src.exceptions.base import AppException
from src.utils.unified_response import FailApiJSONResponse

from .app_exception import app_exception_handler
from .http_exception import http_exception_handler
from .request_validation import validation_exception_handler


async def global_exception_handler(request: Request, exc: Exception):
    """处理服务端异常, 全局异常处理"""
    # 中间件中引发的错误会被全部归为Exception, 因此需要在这边进行异常类型判断后再处理
    if isinstance(exc, AppException):
        response = await app_exception_handler(request, exc)
    elif isinstance(exc, HTTPException):
        response = await http_exception_handler(request, exc)
    elif isinstance(exc, RequestValidationError):
        response = await validation_exception_handler(request, exc)
    else:
        data = {"err_msg": str(exc)}
        # 将错误堆栈信息进行保存
        # logger.error(exc, exc_info=True)
        response = FailApiJSONResponse(
            status_code=HttpResponseEnum.SUCCESS.value.code,
            code=HttpResponseEnum.SERVER_ERROR.value.code,
            data=data,
            message=HttpResponseEnum.SERVER_ERROR.value.msg,
        )
    return response
